angular.module('module.news')
    .controller('NewsGroupController', NewsGroupController);
NewsGroupController.$inject = ['$scope', '$localStorage', '$filter', 'NewsService', '$state'];
function NewsGroupController($scope, $localStorage, $filter, NewsService, $state) {

    var vm = this;
    if (!$localStorage[environmental + "shopid"]) {
        $localStorage.$reset();
        $state.go('login');
    }

    var shopid = $localStorage[environmental + "shopid"];
    var _time = null;
    var map = {};
    vm.unHandleList = [];
    var page = {
        pages: 1,
        pagesize: 10
    };
    //vm.newsArry = new Array(); //
    vm.newsArry = []; //
    vm.allNewsList = [];
    vm.getTableName = getTableName;// 获取桌台名
    vm.firmNews = firmNews; // 处理消息
    vm.history = history; // 历史记录
    vm.openPay = openPay; // 买单操作
    vm.sureBtn = sureBtn; // 模态框
    vm.cancelBtn = cancelBtn; // 模态框

    // 获取未处理的消息
    var myDate = new Date();
    var nowTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate() - 1, 0, 0, 0);

    // 获取一个星期的时间戳
    var endTimes = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), 23, 59, 59);
    var startTime = $filter('date')(nowTime, 'yyyy-MM-dd HH:mm:ss');
    var endTime = $filter('date')(endTimes, 'yyyy-MM-dd HH:mm:ss');

    function sureBtn() {
        vm.messageVisible = false;
    }

    function cancelBtn() {
        vm.messageVisible = false;
    }

    NewsService.getNewsByShopId(shopid, 0, startTime, endTime).$promise.then(function (data) {
        vm.newsArry = data;
        //handle = vm.newsArry; // 多余?
        testAddList(vm.newsArry);
        doClient(newsNote, shopid);
        vm.allNewsList.sort(compare("createtime")); // 消息排序
    }, function (error) {
        vm.newsArry = [];
        doClient(newsNote, shopid);
    });

    // 解析及时通讯返回数据
    function newsNote(topic, payload) {
        var message = JSON.parse(payload);
        var changeBody = JSON.parse(message.body.body);
        var newsDetail = {
            callcontent: changeBody.msg,
            createtime: message.headers.createtime,
            device: changeBody.device,
            handleid: 0,
            handlename: null,
            handletime: null,
            modetype: message.headers.content_type,
            shopid: changeBody.shopid,
            tableid: changeBody.tableid,
        };
        vm.newsArry.push(newsDetail);
        callWaiter(newsDetail);

        // 定时器进行页面时间倒计时
        timeGoOut();
        vm.allNewsList.sort(compare("createtime")); // 消息排序
    }

    // 遍历消息列表进行不同操作
    function testAddList(list) {

        for (var i = 0; i < list.length; i++) {

            // 客户买单操作
            //callBill(list[i]);

            // 客户呼叫操作
            callWaiter(list[i]);
        }

        // 定时器进行页面时间倒计时
        timeGoOut();
    }

    // 通过桌台id获取桌台名称
    function getTableName(item) {
        NewsService.getTableByTableId(item.tableid).$promise.then(function (data) {
            if (data.createtime) {
                item.tablename = data.tablename;
            } else {
                item.tablename = "未知";
            }
        }, function (error) {
        });
    }

    // 处理消息
    function firmNews(dest, newslist) {
        var handleData = [];
        for (var i = 0; i < vm.newsArry.length; i++) {
            if (newslist.tableid == vm.newsArry[i].tableid) {

                // 把数组中桌台id相同的消息都处理掉
                vm.newsArry[i].handleid = 1;
                if (vm.newsArry[i].callcontent == "结账" && vm.text) {
                    vm.newsArry[i].handlecontent = vm.text * 100;
                    handleData.push(vm.newsArry[i]);
                }
            }
        }
        var index = dest.indexOf(newslist);
        NewsService.updateNews(handleData, function (sucData) {
            dest.splice(index, 1);
            if (vm.text) {
                vm.alertVisible = false;
            }
            if (map[newslist.tableid]) {
                delete map[newslist.tableid];
            }

            for (var i = vm.newsArry.length - 1; i >= 0; i--) {
                if (newslist.tableid == vm.newsArry[i].tableid) {
                    vm.newsArry.splice(i, 1);
                }
            }
            window.clearTimeout(_time);
            timeGoOut();
        }, function (error) {
            dest.splice(index, 1, newslist);
        });
    }

    // 计时

    // 定时操作
    function timeGoOut() {
        urgentMsg(vm.allNewsList); // 加急处理
        _time = setTimeout(function () {
            $scope.$apply(function () {
                timeGoOut();
            })
        }, 1000);
    }

    // 超时加急处理
    function urgentMsg(list) {

        for (var j = 0; j < list.length; j++) {
            timeFilter(list[j]);
        }
    }

    // 时间戳过滤成小时分钟秒显示
    function timeFilter(tableNew) {

        if (tableNew) {
            tableNew.time = timeGo(tableNew.createtime, tableNew);
        }
    }

    // 根据时间对数据进行加急分类
    function timeGo(creatime, table) {
        var timeCha = new Date().getTime() - creatime;
        table.timeCha = timeCha;
        if (timeCha > 30 * 1000) {
            table.urgent = true;
        } else {
            table.urgent = false;
        }
        return changeTime(timeCha);
    }

    // 获取已处理的消息
    function history() {
        page.pages = 1;
        vm.unHandleList = [];
        $('#openHistroy').modal('show');

        NewsService.getNewsByPage(shopid, 1, page).$promise.then(function (data) {

            for (var i = 0; i < data.length; i++) {
                if (data[i].callcontent == "呼叫" || data[i].callcontent == "结账") {
                    data[i].time = changeTime((data[i].handletime - data[i].createtime));
                    vm.unHandleList.push(data[i]);
                }
            }

            if (vm.unHandleList.length == 0) {
                vm.flat0 = true;
                vm.load0 = false;
            }
        }, function (error) {
            vm.unHandleList = [];
            vm.flat0 = true;
            vm.load0 = false;
        });
    }

    // 时间戳转换成页面显示时间
    function changeTime(timecha) {
        var day = parseInt(timecha / 3600 / 1000 / 24);
        var hours = parseInt((timecha % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((timecha % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = parseInt((timecha % (1000 * 60)) / 1000);

        if (day > 0) {
            return day + "天"
        } else if (hours > 1) {
            return hours + "小时";
        } else {
            return (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
        }
    }

    // 历史消息滚动加载更多
    $("#openHistroy").scroll(function () {
        var scrollTop = $(this).scrollTop();
        var scrollHeight = $(document).height();
        var idheight = $(".modal-news-content").outerHeight(); // 总高度

        if (idheight > 0) {
            if (scrollTop + scrollHeight >= idheight) {
                if (!vm.load0 && vm.flat0) {
                    vm.load0 = true;
                    vm.flat0 = false;
                    page.pages++;
                    NewsService.getNewsByPage(shopid, 1, page).$promise.then(function (data) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].callcontent == "呼叫" || data[i].callcontent == "结账") {
                                data[i].time = changeTime((data[i].handletime - data[i].createtime));
                                vm.unHandleList.push(data[i]);
                            }
                        }
                        vm.flat0 = true;
                        vm.load0 = false;
                    }, function (error) {
                        //vm.unHandleList = []
                    });
                }
            } else {
                $scope.$apply(function () {
                    vm.flat0 = true;
                    vm.load0 = false;
                });
            }
        }
    });

    // 客户呼叫
    function callWaiter(msg) {
        msg.lowelectricity = msg.callcontent == "低电量" ? 0 : 1;

        // 添加低电量状态
        if (msg.callcontent == "呼叫" || msg.callcontent == "结账" || msg.callcontent == "低电量") {

            // 呼叫情况
            setMsg(map, msg, vm.allNewsList);
        } else if (msg.callcontent == "取消呼叫" || msg.callcontent == "取消结账") {

            // 取消情况
            cancelMsg(map, msg, vm.allNewsList);

            // 判断是否取消正在结账的消息
            if (vm.alertVisible) {
                if (vm.alertMsg.tableid == msg.tableid) {
                    vm.alertVisible = false;
                }
            }
        }
    }

    // 新增信息（呼叫或者买单）
    function setMsg(map, msg, list) {
        if (!map[msg.tableid]) {
            list.push(msg);
            map[msg.tableid] = msg.tableid;
        } else {
            for (var j = 0; j < list.length; j++) {
                if (list[j].tableid == msg.tableid) {
                    if(list[j].lowelectricity == 0 && msg.callcontent != "低电量"){
                        list[j].callcontent = msg.callcontent;
                        list[j].createtime = msg.createtime;
                    }else{
                        if(msg.callcontent == "低电量"){
                            list[j].lowelectricity = msg.lowelectricity;
                        }else{
                            list.splice(j, 1, msg);
                        }
                    }
                }
            }
        }
    }

    // 取消信息（呼叫或者买单）
    function cancelMsg(map, msg, list) {
        if (map[msg.tableid]) {
            for (var j = 0; j < list.length; j++) {
                if (list[j].tableid == msg.tableid) {
                    list.splice(j, 1);
                    delete map[msg.tableid];
                }
            }
        }
    }

    // 买单操作
    function openPay(list, msg) {
        vm.text = "";
        vm.alertVisible = true;
        vm.alertMsg = msg;
        vm.alertData = {
            type: 1, // 1代表输入型，2代表警告型，3代表提醒型
            inputType: "number", //
            btnMsg: [
                {
                    content: '确定',
                    float: false, // 0代表整个，left代表左边，righ代表右边
                    class: '',
                    event: payBill,
                    param: {
                        list: list,
                        msg: msg
                    },
                    term:/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                },
            ],
            contentMsg: {
                top: msg.tablename + '买单',
                center: '请输入客人买单金额'
            }
        };
    }

    // 结账
    function payBill(param) {

        if (vm.text == "" || !vm.text) {
            vm.messageVisible = true;
            vm.message = "请输入金额";
            return;
        }
        firmNews(param.list, param.msg);
    }
}
